import { PageContainer } from '@ant-design/pro-components';
import { message } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import OrderTable from './components/OrderTable';
import SearchBox from './components/SearchBox';

const OrderPage: React.FC = () => {
  type ListItem = {
    id: string;
    content: string;
    status: string;
    createTime: string;
  };
  const [list, setList] = useState<ListItem[]>([]);
  const [searchKey, setSearchKey] = useState('');
  const [status, setStatus] = useState('0');
  const [range, setRange] = useState<[string | null, string | null]>([
    null,
    null,
  ]);

  const handleSearch = (params: {
    status: string;
    range: [string | null, string | null];
    searchKey: string;
  }) => {
    const { status, range, searchKey } = params;
    setStatus(status);
    setSearchKey(searchKey);
    setRange(range);
  };
  useEffect(() => {
    const storedList = localStorage.getItem('list');
    const storedId = localStorage.getItem('id');

    if (storedList && storedId) {
      setList(JSON.parse(storedList));
    } else {
      localStorage.setItem('id', '1');
      localStorage.setItem('list', JSON.stringify([]));
    }
  }, []);
  const handleCreate = (content: string) => {
    const obj = {
      id: localStorage.getItem('id') || '1',
      content,
      status: '1',
      createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    };
    setList([obj, ...list]);
    localStorage.setItem('list', JSON.stringify([obj, ...list]));
    localStorage.setItem(
      'id',
      (parseInt(localStorage.getItem('id') || '1') + 1).toString(),
    );
  };
  const handleFinish = (id: string) => {
    const newarr = list.slice();
    newarr.filter((item) => {
      if (item.id === id) {
        item.status = '2';
      }
      return item;
    });
    console.log(newarr);
    localStorage.setItem('list', JSON.stringify([...newarr]));
    message.success('操作成功');
    setList([...newarr]);
  };
  const getList = () => {
    console.log(range);
    return list.filter((item) => {
      const itemTime = moment(item.createTime, 'YYYY-MM-DD HH:mm:ss');
      const matchesStartDate =
        range[0] === null ||
        range[0] === '' ||
        itemTime.isSameOrAfter(moment(range[0]), 'day');
      const matchesEndDate =
        range[1] === null ||
        range[1] === '' ||
        itemTime.isSameOrBefore(moment(range[1]), 'day');
      return (
        (status === '0' ? true : item.status === status) &&
        item.content.includes(searchKey) &&
        matchesStartDate &&
        matchesEndDate
      );
    });
  };

  return (
    <PageContainer
      ghost
      header={{
        title: '待办事项',
      }}
    >
      <SearchBox onSearch={handleSearch} />
      <OrderTable
        onCreate={handleCreate}
        onFinish={handleFinish}
        data={getList()}
      />
    </PageContainer>
  );
};

export default OrderPage;
